﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace ICodeShare.UI.Controls.Assists
{
    public static class BorderAssist
    {
        #region AutoCornerRadius 获取焦点后选中全部文本

        public static void SetAutoCornerRadius(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoCornerRadiusProperty, value);
        }

        [AttachedPropertyBrowsableForType(typeof(Border))]
        public static bool GetAutoCornerRadius(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoCornerRadiusProperty);
        }

        public static readonly DependencyProperty AutoCornerRadiusProperty = DependencyProperty.RegisterAttached(
            "AutoCornerRadius",
            typeof(bool),
            typeof(BorderAssist),
            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsRender, OnAutoCornerRadiusChanged));

        static void OnAutoCornerRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Border)
            {
                var border = d as Border;

                if ((bool)e.NewValue)
                {
                    border.SizeChanged += border_SizeChanged;

                }
                else
                {
                    border.SizeChanged -= border_SizeChanged;
                }
            }
        }

        static void border_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var border = sender as Border;
            if (border == null)
                return;
            if (GetAutoCornerRadius(border))
            {
                border.CornerRadius = new CornerRadius(border.ActualWidth >= border.ActualHeight ? border.ActualHeight / 2 : border.ActualWidth / 2);
            }
        }
        #endregion
    }
}
